package com.imgo.max.experience.listener;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.imgo.max.artist.dto.DevoteInfo;
import com.imgo.max.common.util.ObjectUtil;
import com.imgo.max.experience.service.PracticerSelfHandler;

/**
 * 练习生专有的增加经验的类，比如直播时长，直播峰值人数
 * Created by peter.Y on 16/07/27.
 */
public class PracticerExprListener implements MessageListener {
	private static final Logger logger = LoggerFactory.getLogger(PracticerExprListener.class);

	@Resource
	PracticerSelfHandler practicerSelfHandler;
	
	@Override
	public Action consume(Message message, ConsumeContext context) {
		DevoteInfo devote = null;
		try {
			logger.trace("msgID:{}, reconsumeTimes:{}", message.getMsgID(), message.getReconsumeTimes());

			devote = (DevoteInfo) ObjectUtil.toObject(message.getBody());
			if (null != devote) {
				devote.setMessageId(message.getMsgID());
				if (logger.isTraceEnabled()) {
					logger.trace("devote aid:{} uid:{} devote value:{},Gid:{}, totalPrice:{}, messageId:{}, coinSeq:{}",
							devote.getArtistUid(), devote.getUid(), devote.getDevoteValue(), devote.getGid(), devote.getTotalPrice(),
							devote.getMessageId(), devote.getCoinSeq());
				}
				//贡献值来源 － 0:加粉丝 1:礼物 2:守护 3:直播时长 4:观看人数 5:每次直播峰值 6发消息
				if (3 == devote.getType() || 4 == devote.getType() || 5 == devote.getType())
				{
					// 记录经验
					practicerSelfHandler.record(devote);
				}

				
			} else {
				final Integer bodyLen = message.getBody() != null ? message.getBody().length : null;
				logger.warn("反序列化DevoteInfo结果为null, 可能是ObjectUtil.toObject()出错, msgID:{}, body.length:{}", message.getMsgID(), bodyLen);
			}

		} catch (Exception e) {
			if(devote != null) {
				logger.error("devote aid:{} uid:{} devote value:{},Gid:{}, totalPrice:{}, messageId:{}, coinSeq:{}",
						devote.getArtistUid(), devote.getUid(), devote.getDevoteValue(), devote.getGid(), devote.getTotalPrice(),
						devote.getMessageId(), devote.getCoinSeq());
			}
			logger.error(e.getMessage(), e);
			return Action.ReconsumeLater;
		}

		return Action.CommitMessage;
	}

}
